<template>
  <FormTableCardComp>
    <template #form>
      <t-form ref="form" :data="dictSearch" scroll-to-first-error="smooth" layout="inline" colon @reset="onReset"
        @submit="onSubmit">
        <t-form-item labelWidth="0">
          <t-input v-model="dictSearch.name" placeholder="请输入字典名称或字典编码"></t-input>
        </t-form-item>
        <t-form-item labelWidth="0">
          <t-space size="small">
            <t-button theme="primary" type="submit">提交</t-button>
            <t-button theme="default" variant="base" type="reset">重置</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </template>
    <template #table>
      <t-table v-model:columnControllerVisible="dictState.columnControllerVisible" row-key="dictId"
        :data="dictState.tableData" :columns="columns" lazy-load bordered
        :pagination="{ defaultPageSize: 5, defaultCurrent: 1, total: 100000 }"
        :column-controller="columnControllerConfig" :loading="dictState.loading">
        <template #topContent>
          <TableToolbar>
            <template #toolbarLeft>
              <t-button theme="primary" @click="dictEdit('add')">
                新增
              </t-button>
            </template>
            <template #toolbarRight>
              <t-tooltip content="刷新">
                <t-button shape="circle" variant="text">
                  <template #icon>
                    <RefreshIcon />
                  </template>
                </t-button>
              </t-tooltip>
              <t-tooltip content="列表配置">
                <t-button shape="circle" variant="text" @click="dictState.columnControllerVisible = true">
                  <template #icon>
                    <SettingIcon />
                  </template>
                </t-button>
              </t-tooltip>
            </template>
          </TableToolbar>
        </template>

        <!-- <template #dictType="{ row }">
          <t-link theme="primary" @click="toDictDataView(row)">{{ row.dictType }}</t-link>
        </template> -->

        <template #status="{ row }">
          <re-status :status="row.status" />
        </template>

        <template #options="{ row }">
          <t-space size="small">
            <t-link theme="primary" @click="dictEdit('edit', row)"> 编辑 </t-link>
            <t-popconfirm v-model="dictState.delConfirmVisible" theme="danger" content="确定删除该字典"
              @confirm="delDict(row)">
              <t-link theme="danger"> 删除 </t-link>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
    </template>
  </FormTableCardComp>

  <!-- 字典项编辑 -->
  <t-dialog v-model:visible="dictState.dictVisible" :header="dictState.dictEditTitle" @confirm="dictSubmit"
    @closed="dictClose">
    <t-form ref="dictFormRef" :data="dictState.dictRow" :rules="dictRules" scroll-to-first-error="smooth" colon>

      <t-form-item label="字典名称" name="dictName">
        <t-input v-model="dictState.dictRow.dictName" placeholder="请输入字典名称" />
      </t-form-item>
      <t-form-item label="字典编码" name="dictType">
        <t-input v-model="dictState.dictRow.dictType" placeholder="请输入字典编码" />
      </t-form-item>
      <t-form-item label="备注" name="remarks">
        <t-textarea v-model="dictState.dictRow.remarks" placeholder="请输入备注" :autosize="{ minRows: 5, maxRows: 5 }" />
      </t-form-item>
      <t-form-item label="状态" name="status">
        <t-switch v-model="dictState.dictRow.status" :label="['有效', '无效']" :custom-value="[0, 1]" />
      </t-form-item>

    </t-form>
  </t-dialog>

</template>

<script setup lang="ts">
import { SysDict } from '@/api/model/sys';
import { FormTableCardComp } from '@/components/ReCard';
import { ReStatus } from '@/components/ReStatus';
import { TableToolbar } from '@/components/ReTable';
import { RefreshIcon, SettingIcon } from 'tdesign-icons-vue-next';
import { FormInstanceFunctions, FormProps, FormRules, MessagePlugin, TableProps } from 'tdesign-vue-next';

// ---------------------------------------
const dictSearch = reactive({
  name: '',
})

const onReset: FormProps['onReset'] = () => {
  MessagePlugin.success('重置成功');
};

const onSubmit: FormProps['onSubmit'] = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    MessagePlugin.success('提交成功');
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError as string);
  }
};

interface dictStateType {
  loading: boolean;
  columnControllerVisible: boolean;
  tableData: Array<SysDict>,
  //
  dictEditTitle: string,
  dictVisible: boolean,
  dictRow: SysDict,
  // 删除
  delConfirmVisible: boolean,
}

const dictState = reactive<dictStateType>({
  loading: false,
  columnControllerVisible: false,
  tableData: [
    {
      dictId: '1',
      dictName: '测试111',
      dictType: 'Test1',
      remarks: '备注',
      status: 0,
      createTime: '2022-01-01',
      updateTime: '2022-01-01',
      createBy: 'admin',
      updateBy: 'admin',
    }
  ],
  //
  dictEditTitle: '',
  dictVisible: false,
  dictRow: {
    dictId: '',
    dictName: '',
    dictType: '',
    remarks: '',
    status: 0,
    createTime: '',
    updateTime: '',
    createBy: '',
    updateBy: '',
  },
  // 删除
  delConfirmVisible: false,
});

// @ts-ignore
const columns: TableProps['columns'] = [
  { colKey: 'serial-number', width: '75', title: '序号', align: 'center', },
  {
    colKey: 'roleName',
    title: '角色名称',
    width: '200',
  },
  {
    colKey: 'roleCode',
    title: '角色编码',
    width: '200',
  },
  {
    colKey: 'remarks',
    title: '备注',
    width: '200',
  },
  {
    colKey: 'status',
    title: '状态',
    width: '50',
    align: 'center'
  },

  {
    colKey: 'options',
    title: '操作',
    width: '200',
    fixed: 'right',
  },
];

// 列配置
const columnControllerConfig = computed(() => ({
  hideTriggerButton: true,
  // 允许哪些列参与显示-隐藏控制
  fields: ['dictName', 'dictCode', 'remarks',],
  // 透传弹框组件全部属性
  dialogProps: { preventScrollThrough: true },
}));

const dictFormRef = ref<FormInstanceFunctions<SysDict>>();

// 校验规则
const dictRules: FormRules<any> = {
  dictName: [
    { required: true, message: '请输入字典名称', type: 'error' },
    { max: 20, message: '字典名称应在20字以内', type: 'error', trigger: 'blur' },
  ],
  dictType: [
    { required: true, message: '请输入字典编码', type: 'error' },
    { max: 20, message: '字典编码应在20字以内', type: 'error', trigger: 'blur' },
  ],
  remarks: [
    { min: 0, max: 200, message: '备注在200字以内', type: 'error', trigger: 'blur' },
  ],
}

const dictEdit = (type: string, row?: any) => {
  if (type === 'add') {
    dictState.dictEditTitle = '新增字典';
    dictState.dictVisible = true;
  } else if (type === 'edit') {
    dictState.dictEditTitle = '编辑字典';
    dictState.dictRow = { ...row };
    dictState.dictVisible = true;
  }
  console.log('dictRow', dictState.dictRow);
}

const dictSubmit = () => {
  dictFormRef.value?.validate().then((validateResult) => {
    if (validateResult === true) {
      MessagePlugin.success('提交成功');
      dictState.dictVisible = false;
    }
  });
}

const dictClose = () => {
  dictFormRef.value?.reset({
    type: 'initial',
  });
}

const delDict = (res: SysDict) => {
  console.log('delDict', res);

}

// ---------------------------------------

</script>

<style scoped></style>
